<template>
  <div class="transfer-page"></div>
</template>
<script lang="ts" setup>
  import { useDictStoreWithOut } from '@/store/modules/dict'
  import { useUserStoreWithOut } from '@/store/modules/user'
  import { getUserProfile } from '@/api/system/user/profile'
  import { useRouter } from 'vue-router'
  import * as LoginApi from '@/api/login'
  import * as authUtil from '@/utils/auth'

  const { push } = useRouter()
  const userId = ref()

  const freeLogin = async () => {
    ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    const dictStore = useDictStoreWithOut()
    const res = await LoginApi.switchDispatchServer({ userAccountId: userId.value })
    authUtil.setToken(res)
    authUtil.setUserId(res.userId)
    authUtil.setTenantId(res.tenantId)
    await dictStore.setDictMap()
    await dictStore.setJLDictMap()
    getTenantList()
    push({ path: '/' })
    setTimeout(() => {
      const loadingInstance = ElLoading.service()
      loadingInstance.close()
    }, 400)
  }

  const getTenantList = async () => {
    const userStore = useUserStoreWithOut()
    const res = await getUserProfile()
    authUtil.setLoginForm({
      account: res.username,
      loginType: 1
    })
    userStore.getTenantList()
  }

  const getUrlParams = (url) => {
    const params = {};
    const query = url.split('?')[1]
    if (query) {
      const queryParts = query.split("&");
      queryParts.forEach((part) => {
        const [key, value] = part.split("=");
        params[key] = decodeURIComponent(value);
      });
    }
    return params;
  }

  onMounted(() => {
    authUtil.clearCacheAll()
    const params = getUrlParams(location.href)
    userId.value = params?.userId
    freeLogin()
  })
</script>
<style lang="scss" scpoed>
  .transfer-page {
    width: 100wh;
    height: 100vh;
  }
</style>